const app = getApp()
const config = app.globalData.config

Page({
  data: {
    activities: []
  },

  onLoad: function (options) {
    // 检查登录状态
    this.checkLoginStatus()
  },

  onShow: function () {
    // 只在需要刷新时检查登录状态
    if (app.globalData.needRefresh) {
      this.checkLoginStatus()
      app.globalData.needRefresh = false
    }
  },

  onPullDownRefresh: function () {
    this.loadActivities()
  },

  // 检查登录状态
  checkLoginStatus() {
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('userInfo')
    const isCoach = wx.getStorageSync('isCoach')
    
    if (userInfo && isCoach) {
      // 更新全局数据
      app.globalData.userInfo = userInfo
      app.globalData.isCoach = true
      // 加载活动列表
      this.loadActivities()
    } else {
      // 跳转到登录页
      wx.navigateTo({
        url: '/pages/coach/login/login'
      })
    }
  },

  loadActivities: function () {
    wx.showLoading({
      title: '加载中',
    })

    // 获取存储的cookies
    const cookies = wx.getStorageSync('cookies')
    if (!cookies) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/coach/login/login'
            })
          }, 1500)
        }
      })
      return
    }

    // 获取教练ID
    const coachId = app.globalData.userInfo?.coachId
    if (!coachId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/coach/login/login'
            })
          }, 1500)
        }
      })
      return
    }
    console.log(coachId);
    // 调用后端API获取活动列表
    wx.request({
      url: config.baseUrl[config.env] + '/coach/activities',
      method: 'POST',
      header: {
        'Cookie': cookies,
        'Content-Type': 'application/json'
      },
      data: {
        coachId: coachId,
        activityName: '',
        activityDesc: '',
        activityDays: null,
        totalPeople: null,
        imagePath: '',
        activityTheme: '',
        teamCount: null,
        teamSize: null,
        dailyStartTime: null,
        dailyEndTime: null,
        activityStatus: null,
        createTime: null,
        updateTime: null
      },
      success: res => {
        const { errorCode, data } = res.data
        if (errorCode === '000000') {
          // 处理图片路径
          const activities = data
          this.setData({
            activities: activities
          })
        } else {
          // 如果是未登录状态，跳转到登录页
          if (errorCode === '401') {
            // 清除登录信息
            wx.removeStorageSync('userInfo')
            wx.removeStorageSync('isCoach')
            wx.removeStorageSync('cookies')
            app.globalData.userInfo = null
            app.globalData.isCoach = false
            
            wx.navigateTo({
              url: '/pages/coach/login/login'
            })
          } else {
            wx.showToast({
              title: '获取活动列表失败',
              icon: 'none'
            })
          }
        }
      },
      fail: err => {
        console.error('获取活动列表失败：', err)
        wx.showToast({
          title: '获取活动列表失败',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
        wx.stopPullDownRefresh()
      }
    })
  },

  navigateToCreate: function () {
    wx.navigateTo({
      url: '/pages/coach/createActivity/createActivity'
    })
  },

  navigateToDetail: function (e) {
    const activity = e.currentTarget.dataset.item;
    // 将活动信息转换为字符串
    const activityStr = JSON.stringify(activity);
    wx.navigateTo({
      url: `/pages/coach/activityDetail/activityDetail?activity=${encodeURIComponent(activityStr)}`
    })
  }
}) 